package day5.LC541;

public class Main {
    public static void main(String[] args) {
        String str=new String("abcdefg");
        int k=2;
        new Solution().reverseStr(str,k);
    }
}


class Solution {
    public String reverseStr(String s, int k) {
        StringBuilder stringBuilder = new StringBuilder();
        //处理尾部
        int remainder = (s.length()) % (2 * k);
        StringBuilder tail=new StringBuilder();
        if (remainder < k) {
            //将剩余字符全部反转
            String substring = s.substring(s.length() - remainder);
            StringBuilder reverseTail = new StringBuilder(substring).reverse();
            tail.append(reverseTail);
        } else {
            //则反转前 k 个字符，其余字符保持原样
            String sub = s.substring(s.length() - remainder);
            String str = sub.substring(0, k);
            StringBuilder reverse = new StringBuilder(str).reverse();
            tail.append(reverse);
            tail.append(sub.substring(k));
        }
        //处理其他
        String str = s.substring(0, s.length() - remainder);
        while (str != null && str!="") {
            String tempStr = str.substring(0, k);
            StringBuilder reverse = new StringBuilder(tempStr).reverse();
            stringBuilder.append(reverse);
            stringBuilder.append(str.substring(k,2*k));
            str=str.substring(2*k);
        }
        return stringBuilder.append(tail).toString();
    }
}